#!/bin/bash

API_BASE="http://localhost:3002/api/v1"

echo "🔧 Testing Admin Functions"
echo ""

# 1. 登录获取管理员token（假设testdev已经是管理员）
echo "1. Login as admin (testdev)"
LOGIN_RESPONSE=$(curl -s -X POST "$API_BASE/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "testdev@example.com",
    "password": "password123"
  }')

echo "Login response: $LOGIN_RESPONSE"

# 简单提取token（假设响应格式正确）
ADMIN_TOKEN=$(echo "$LOGIN_RESPONSE" | grep -o '"accessToken":"[^"]*"' | cut -d'"' -f4)

if [ "$ADMIN_TOKEN" = "null" ] || [ -z "$ADMIN_TOKEN" ]; then
  echo "❌ Admin login failed"
  exit 1
fi

echo "✅ Admin login successful"
echo "Token: $ADMIN_TOKEN"
echo ""

# 2. 测试系统统计
echo "2. Get system statistics"
curl -s -X GET "$API_BASE/admin/stats" \
  -H "Authorization: Bearer $ADMIN_TOKEN"
echo ""
echo ""

# 3. 测试获取待审核插件
echo "3. Get pending plugins"
curl -s -X GET "$API_BASE/admin/plugins/pending" \
  -H "Authorization: Bearer $ADMIN_TOKEN"
echo ""
echo ""

# 4. 测试获取用户列表
echo "4. Get users list"
curl -s -X GET "$API_BASE/admin/users" \
  -H "Authorization: Bearer $ADMIN_TOKEN"
echo ""
echo ""

# 5. 测试获取审计日志
echo "5. Get audit logs"
curl -s -X GET "$API_BASE/admin/audit-logs" \
  -H "Authorization: Bearer $ADMIN_TOKEN"
echo ""
echo ""

# 6. 测试用户搜索
echo "6. Search users"
curl -s -X GET "$API_BASE/admin/users?search=test&page=1&limit=10" \
  -H "Authorization: Bearer $ADMIN_TOKEN"
echo ""
echo ""

# 7. 测试非管理员访问（应该失败）
echo "7. Test non-admin access (should fail)"
echo "Note: testdev is now admin, so this test will actually succeed"
echo ""

echo "🎉 Admin function testing completed!"
